<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Sitecategory_model extends My_Model
{    
    public function __construct()
    {
        parent::__construct();
        $this->model_name="站点分类";
        $this->tablename="sites_category";  
    }



    public function getall(){
        
        $where=[];

        return $this->get_items_by_where($where);                
    }

    public function getcat($siteid)
    {
        $where=["pid"=>0,"siteid"=>$siteid];
        $cats=$this->get_items_by_where($where,"sort asc");
        if($cats):
        foreach($cats as &$item)
        {
            $where=["pid"=>$item["id"],"siteid"=>$siteid];
            $item["sub"]=$this->get_items_by_where($where,"sort asc");
        }
        endif;
        return $cats;
    }
    public function getroot($siteid)
    {
        $where['pid']=0;
        $where['siteid']=$siteid;
        return $this->get_items_by_where($where);
    }

    public function getchildren($id)
    {
        $where['pid']=$id;
        return $this->get_items_by_where($where);
    }

    public function delitem($id)
    {
        $where=["id"=>$id];
        $this->delete($where);
        return true;
    }

    public function getitembyid($id){
        $where=array("id"=>$id);
        return $this->get_item_by_where($where);
    }


    public function update_insert($catinfo,$siteid)
    {
        $catename = urldecode($catinfo["text"]);
        $where=["siteid"=>$siteid,"rid"=>$catinfo["id"]];
        $row=$this->get_item_by_where($where);
        if($row)
        {            
            if($row["name"]!=$catename)
            {
                $this->update($row["id"],["name"=>$catename]);
            }
        }
        else
        {
            $new=[
                "name"=>$catename,
                "siteid"=>$siteid,
                "rid"=>$catinfo["id"]
            ];
            $this->create($new);
        }
    }
    
    public function create($data){
        if(!isset($data["addtime"])){
            $data["addtime"]=date("Y-m-d H:i:s");
        }
       
        return $this->add_item($data);       
    }

    public function update($id,$data){

        if(is_array($id))
        {
            $where="id in (".implode(",",$id).")";
           
        }else{
            $where=array("id"=>$id);
           
        }
        return $this->update_item($where,$data);

    }

   
}
